package com.bmd.backgroundmanger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bmd.backgroundmanger.commons.BusinessException;
import com.bmd.backgroundmanger.commons.JwtUtil;
import com.bmd.backgroundmanger.entity.User;
import com.bmd.backgroundmanger.mapper.UserMapper;
import com.bmd.backgroundmanger.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 坤哥
 * @since 2024-07-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
   //注入持久层
    @Resource
    private UserMapper userMapper;
    //注入JWTUtil
    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean userRegisterService(User user) {
        // 参数校验
        if (user == null || user.getUsername() == null || user.getUsername().trim().isEmpty()) {
           throw new BusinessException(409,"用户信息不完整");
        }

        // 密码校验
        String password = user.getPassword();
        if (password == null || password.trim().isEmpty()) {
            throw new BusinessException(409,"密码不能为空");
        }

        //1.判断用户名是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        User existingUser = userMapper.selectOne(wrapper);
        
        if (existingUser != null) {
            // 用户名存在
            throw new BusinessException(409,"用户名已存在");
        }
        
        // 将password字段的值复制到passwordHash字段（这里简化处理，实际生产环境应该加密）
        user.setPasswordHash(password);
        
        // 设置默认状态为启用
        if (user.getStatus() == null) {
            user.setStatus(1);
        }
        
        // 设置创建时间
        user.setCreateTime(LocalDateTime.now());
        
        System.out.println("准备注册用户: " + user.getUsername() + ", 密码: " + user.getPasswordHash());
        
        // 执行插入操作
        int insert = userMapper.insert(user);
        System.out.println("注册结果: " + (insert > 0 ? "成功" : "失败"));
        
        return insert > 0;  // 如果大于0,注册成功
    }

    @Override
    public Map<String, Object> userLoginService(String username, String password) {
        Map<String, Object> map = new HashMap<>();
        
        // 先根据用户名查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User loginUser = userMapper.selectOne(wrapper);
        
        if (loginUser == null) {
            // 用户不存在
            throw new BusinessException(400,"账号或密码错误");
        }
        
        // 验证密码（这里简化处理，实际应该使用BCrypt等加密方式）
        // 如果数据库中存储的是明文密码，直接比较
        // 如果是哈希密码，需要使用相应的验证方法
        if (!password.equals(loginUser.getPasswordHash())) {
            // 密码错误
            throw new BusinessException(400,"账号或密码错误");
        }
        
        // 登录成功
        // 生成Token(令牌)
        loginUser.setPasswordHash(null);
        String token = jwtUtil.createToken(loginUser);
        map.put("token", token);
        map.put("user", loginUser);
        return map;
    }

    // 登录初始化
    @Override
    public Map<String, Object> userInfoService(String token) {
        try {
            Map<String, Object> map = new HashMap<>();
            // 解析token
            User user = jwtUtil.parseToken(token, User.class);
            
            System.out.println("从Token解析的用户信息: " + user);
            
            // 重新从数据库查询完整的用户信息，确保数据是最新的
            User fullUser = userMapper.selectById(user.getUserId());
            if (fullUser == null) {
                throw new BusinessException(400,"用户不存在");
            }
            
            System.out.println("从数据库查询的完整用户信息: " + fullUser);
            
            // 返回完整的用户信息
            map.put("id", fullUser.getUserId());
            map.put("userId", fullUser.getUserId()); // 添加userId字段
            map.put("avatar", fullUser.getProfilePictureUrl());
            map.put("name", fullUser.getUsername());
            map.put("username", fullUser.getUsername()); // 添加username字段
            map.put("phone", fullUser.getPhoneNumber());
            map.put("phoneNumber", fullUser.getPhoneNumber()); // 添加phoneNumber字段
            map.put("email", fullUser.getEmail());
            map.put("profilePictureUrl", fullUser.getProfilePictureUrl()); // 添加profilePictureUrl字段
            map.put("status", fullUser.getStatus());
            
            // 也可以直接返回user对象，便于前端处理
            map.put("user", fullUser);
            
            System.out.println("返回给前端的用户信息: " + map);
            
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(400,"token解析错误: " + e.getMessage());
        }
    }
}
